package com.netty.common.scanner;

import java.lang.reflect.Method;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import com.netty.common.core.annotion.RequestMapping;
import com.netty.common.core.annotion.Controller;
@Component
public class Scanner implements BeanPostProcessor{

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		Class<? extends Object> clazz = bean.getClass();
		Class<?>[] interfaces = clazz.getInterfaces();//获取实现的接口，查看接口有没有标注注解
		if (interfaces != null && interfaces.length > 0) {
			for (Class<?> interFace : interfaces) {
				Controller controller = interFace.getAnnotation(Controller.class);
				if (controller == null) {
					continue;
				}
				RequestMapping classMapping = interFace.getAnnotation(RequestMapping.class);
				StringBuffer path = new StringBuffer();
				if (classMapping != null) {
					String[] value = classMapping.value();
					if (value != null && value.length > 0) {
						maping2path(path, value);
					}
				}
				Method[] methods = interFace.getMethods();
				if (methods == null || methods.length <= 0) {
					continue;
				}
				for (Method method : methods) {
					
					RequestMapping methodMapping = method.getAnnotation(RequestMapping.class);
					if (methodMapping == null) {
						continue;
					}
					String[] value = methodMapping.value();
					if (value == null || value.length <= 0) {
						path.append("/"+method.getName());
					}else {
						maping2path(path, value);
					}
					Invoker invoker = Invoker.valueOf(bean, method);
					if (InvokerHolder.getInvoker(path.toString()) == null) {
						InvokerHolder.addInvoker(path.toString(), invoker);
					}else {
						System.out.println("重复注册执行器mapping：【"+path.toString()+"】");
					}
				}
				
			}
		}
		return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
	}
	/**
	 * 映射转path
	 * @param path
	 * @param value
	 */
	private void maping2path(StringBuffer path, String[] value) {
		for (String str : value) {
			if (!str.contains("/")) {
				path.append("/"+str);
			}else {
				path.append(str);
			}
		}
	}
}
